<template>
  <div class="app-container">
    <!-- 装饰元素 -->
    <div class="decoration leaf-1">
      <i class="fas fa-leaf"></i>
    </div>
    <div class="decoration leaf-2">
      <i class="fas fa-leaf"></i>
    </div>

    <!-- 对话区域 -->
    <div class="chat-container" ref="chatContainer">
      <!-- 初始对话 -->
      <div class="message assistant fade-in">
        <div class="avatar">
          <i class="fas fa-dove"></i>
        </div>
        <div class="message-bubble">
          好的，我感受到了你的温暖，让我们一起评估一下他/她的情况，希望能给到一些支持。
        </div>
      </div>

      <div class="message assistant fade-in" style="animation-delay: 0.2s">
        <div class="avatar">
          <i class="fas fa-dove"></i>
        </div>
        <div class="message-bubble">首先我们需要明确本次沟通的员工信息。</div>
      </div>

      <!-- 动态生成的消息区域 -->
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.type, 'fade-in']"
      >
        <div class="avatar">
          <i
            :class="
              message.type === 'assistant' ? 'fas fa-dove' : 'fas fa-user'
            "
          ></i>
        </div>
        <div class="message-bubble">
          <div v-if="message.type === 'assistant' && message.question">
            {{ message.question }}
            <div v-if="message.options" class="options-container">
              <button
                v-for="(option, optIndex) in message.options"
                :key="optIndex"
                :class="[
                  'option-btn',
                  { selected: isOptionSelected(message.id, option) },
                ]"
                @click="selectOption(message.id, option)"
                :disabled="message.answered"
              >
                {{ option }}
              </button>
            </div>
          </div>
          <div v-else-if="message.type === 'assistant' && message.content">
            <div v-if="message.isHtml" v-html="message.content"></div>
            <div v-else>{{ message.content }}</div>
          </div>
          <div v-else-if="message.type === 'user'">
            {{ message.content }}
          </div>
        </div>
      </div>

      <!-- 评估完成后的结果展示 -->
      <div v-if="showFinalResult" class="message assistant fade-in">
        <div class="avatar">
          <i class="fas fa-dove"></i>
        </div>
        <div class="message-bubble">
          <div style="font-weight: 600; margin-bottom: 12px; color: #333">
            评估已完成
          </div>
          <div style="margin-bottom: 16px">
            感谢您完成评估！以下是评估结果：
          </div>

          <!-- 风险等级展示 -->
          <div
            v-if="apiResult"
            style="
              background: #f8f7fc;
              padding: 16px;
              border-radius: 8px;
              margin-bottom: 16px;
              border-left: 4px solid #8e7cc3;
            "
          >
            <div style="font-weight: 600; margin-bottom: 8px; color: #333">
              风险等级：<span :style="getRiskLevelStyle(apiResult.riskLevel)">{{
                apiResult.riskLevel
              }}</span>
            </div>
            <div
              style="font-size: 14px; line-height: 1.6; color: #666"
              v-html="apiResult.info"
            ></div>
          </div>

          <div v-else style="text-align: center; color: #999; padding: 20px">
            <i class="fas fa-spinner fa-spin" style="margin-right: 8px"></i>
            正在生成评估结果...
          </div>
        </div>
      </div>

      <!-- 输入指示器 -->
      <div class="typing-indicator" v-if="isTyping">
        <div class="avatar">
          <i class="fas fa-dove"></i>
        </div>
        <div class="message-bubble">
          <div class="typing-dot"></div>
          <div class="typing-dot"></div>
          <div class="typing-dot"></div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container" v-if="showInput">
      <input
        type="text"
        class="text-input"
        v-model="userInput"
        placeholder="请输入..."
        autocomplete="off"
        @keypress.enter="sendMessage"
        @input="updateSendButton"
      />
      <button
        class="send-btn"
        @click="sendMessage"
        :disabled="!userInput.trim()"
      >
        <i class="fas fa-paper-plane"></i>
      </button>
    </div>
  </div>
</template>

<script>
import { saveEvoQuestion } from "../../api/manager";

export default {
  name: "PsychologicalAssessment",
  data() {
    return {
      // 对话数据 - 使用你提供的他评问题
      conversation: [
        {
          type: "info",
          question: "请问这位员工叫什么名字？",
          field: "employeeName",
        },
        {
          type: "info",
          question: "这位员工属于哪个部门？",
          field: "employeeDepartment",
        },
        {
          type: "intro",
          content:
            " 请根据您近期观察到同事的行为或表现进行填写，您的反馈将匿名化处理，评估结果仅用于制定支持方案，请您放心填写。 ",
        },
        // 替换为你提供的他评问题
        {
          type: "question",
          id: 1282,
          question: "1. 容易烦躁、发怒或情绪起伏很大？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1283,
          question: "2. 多次与同事发生争执或冲突？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1284,
          question: "3. 表现出持续的情绪低落、沮丧或缺乏活力？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1285,
          question: "4. 对原本感兴趣的活动失去热情？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1286,
          question: "5. 比往常孤僻、敏感、多疑等？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1287,
          question: "6. 胡言乱语、行为怪异（如：突然大喊大叫）？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1288,
          question: "7. 透露出想轻生的念头或企图（如：托人/托事/托物）？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1289,
          question: "8. 经常出现无故缺勤、迟到或早退的情况？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1290,
          question: "9. 工作效率明显下降？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1291,
          question: "10. 工作质量不达标，频繁出现错误或失误？",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "question",
          id: 1292,
          question: "11. 经历了生活或工作中的重大变故（如家人去世，离异等）?",
          options: ["有", "无", "不清楚"],
        },
        {
          type: "text",
          id: 1293,
          question: "12. 其他想要反馈的情况：",
        },
        {
          type: "completion",
          content: "正在上传结果...",
        },
      ],
      // 应用状态
      currentStep: 0,
      answers: {},
      messages: [],
      userInput: "",
      isTyping: false,
      showInput: false,
      activeTab: "home",
      showFinalResult: false,
      finalAnswers: [],
      apiResult: null, // 存储API返回的结果
    };
  },
  mounted() {
    // 初始化应用
    this.initApp();
    if (!localStorage.getItem("userId")) {
      this.$router.push("/minsheng/login");
    }
  },
  methods: {
    initApp() {
      // 显示第一个问题
      setTimeout(() => {
        this.showNextStep();
      }, 1500);
    },

    setActiveTab(tab) {
      this.activeTab = tab;
      // 在实际应用中，这里会加载对应标签的内容
      if (tab === "home") {
        this.$router.push("/managerHome");
      } else if (tab === "referral") {
        this.$router.push("/yijianzhuanjie");
      } else if (tab === "resources") {
        this.$router.push("/weijiganyu");
      }
    },

    showNextStep() {
      if (this.currentStep >= this.conversation.length) {
        // 所有问题已完成，显示最终结果
        this.showFinalResults();
        return;
      }

      const step = this.conversation[this.currentStep];

      // 显示输入指示器
      this.isTyping = true;
      this.scrollToBottom();

      // 根据步骤类型处理
      setTimeout(() => {
        this.isTyping = false;

        if (step.type === "info") {
          this.showInfoQuestion(step);
        } else if (step.type === "intro") {
          this.showIntroMessage(step);
        } else if (step.type === "question") {
          this.showQuestion(step);
        } else if (step.type === "text") {
          this.showTextQuestion(step);
        } else if (step.type === "completion") {
          this.showCompletionMessage(step);
        }

        this.scrollToBottom();
      }, 1000);
    },

    showInfoQuestion(step) {
      this.messages.push({
        type: "assistant",
        question: step.question,
      });

      // 启用文本输入
      this.showInput = true;
      this.$nextTick(() => {
        const input = this.$el.querySelector(".text-input");
        if (input) input.focus();
      });
    },

    showIntroMessage(step) {
      this.messages.push({
        type: "assistant",
        content: step.content,
      });

      this.currentStep++;
      setTimeout(() => {
        this.showNextStep();
      }, 1500);
    },

    showQuestion(step) {
      this.messages.push({
        type: "assistant",
        id: step.id,
        question: step.question,
        options: step.options,
        answered: false,
      });

      // 隐藏输入区域
      this.showInput = false;
    },

    showTextQuestion(step) {
      this.messages.push({
        type: "assistant",
        question: step.question,
      });

      // 启用文本输入
      this.showInput = true;
      this.$nextTick(() => {
        const input = this.$el.querySelector(".text-input");
        if (input) input.focus();
      });
    },

    showCompletionMessage(step) {
      this.messages.push({
        type: "assistant",
        content: step.content,
      });

      // 隐藏输入区域
      this.showInput = false;

      // 生成最终答案并提交
      this.generateFinalAnswers();
    },

    isOptionSelected(questionId, option) {
      return this.answers[questionId] === option;
    },

    selectOption(questionId, option) {
      // 保存答案
      this.answers[questionId] = option;

      // 标记问题已回答
      const message = this.messages.find((m) => m.id === questionId);
      if (message) {
        message.answered = true;
      }

      // 显示用户的选择
      this.showUserMessage(option);

      // 下一步
      this.currentStep++;
      setTimeout(() => {
        this.showNextStep();
      }, 1000);
    },

    showFinalResults() {
      this.showFinalResult = true;
      this.scrollToBottom();
    },

    generateFinalAnswers() {
      // 按照你要求的格式生成答案数组
      const questionIds = [
        1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293,
      ];

      this.finalAnswers = questionIds.map((id) => {
        const answer = this.answers[id];
        if (id === 1293) {
          // 最后一个问题是文本输入，如果没有答案则显示"无"
          return answer && answer.trim() !== "" ? answer : "无";
        } else {
          // 选择题，如果没有答案则显示"不清楚"
          return answer || "不清楚";
        }
      });

      console.log("最终答案数组:", this.finalAnswers);

      // 调用API提交数据
      this.submitAssessment(this.finalAnswers);
    },

    showUserMessage(content) {
      this.messages.push({
        type: "user",
        content: content,
      });

      this.scrollToBottom();
    },

    updateSendButton() {
      // Vue的响应式系统会自动处理按钮状态
    },

    sendMessage() {
      const message = this.userInput.trim();
      if (!message) return;

      // 显示用户消息
      this.showUserMessage(message);

      // 保存答案
      const step = this.conversation[this.currentStep];
      if (step.type === "info") {
        this.answers[step.field] = message;
      } else if (step.type === "text") {
        this.answers[step.id] = message;
      }

      // 清空输入框
      this.userInput = "";

      // 下一步
      this.currentStep++;
      setTimeout(() => {
        this.showNextStep();
      }, 1000);
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    // 根据风险等级返回样式
    getRiskLevelStyle(riskLevel) {
      const styles = {
        低: { color: "#52c41a", fontWeight: "bold" },
        中: { color: "#faad14", fontWeight: "bold" },
        高: { color: "#f5222d", fontWeight: "bold" },
      };
      return styles[riskLevel] || { color: "#333", fontWeight: "bold" };
    },

    // 添加提交方法以匹配你的API
    async submitAssessment(answerArray) {
      const submitData = {
        name: this.answers.employeeName,
        bumen: this.answers.employeeDepartment,
        data: answerArray,
        starttime: this.getCurrentTimeWithSeconds(),
        userId: localStorage.getItem("userId"),
      };

      try {
        const res = await saveEvoQuestion(submitData);

        if (res && res.code === 200 && res.data) {
          // 存储API返回的结果
          this.apiResult = res.data;
          console.log("API返回结果:", this.apiResult);

          // 显示最终结果
          setTimeout(() => {
            this.showFinalResults();
          }, 500);
        } else {
          console.error("API返回异常:", res);
          // 即使API异常也显示结果界面
          setTimeout(() => {
            this.showFinalResults();
          }, 500);
        }
      } catch (err) {
        console.error("提交失败：", err);
        // 即使出错也显示结果界面
        setTimeout(() => {
          this.showFinalResults();
        }, 500);
      }
    },

    getCurrentTimeWithSeconds() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      const hour = now.getHours();
      const minute = now.getMinutes();
      const second = now.getSeconds();

      return `${year}-${month < 10 ? "0" + month : month}-${
        day < 10 ? "0" + day : day
      } ${hour}:${minute < 10 ? "0" + minute : minute}:${
        second < 10 ? "0" + second : second
      }`;
    },
  },
};
</script>

<style scoped>
/* 样式保持不变，与您之前的代码相同 */
.app-container {
  max-width: 414px;
  margin: 0 auto;
  background: linear-gradient(to bottom, #f8f7fc, #f0edf9);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
}

/* 对话区域 */
.chat-container {
  padding: 30px 12px;
  padding-bottom: 100px;
  height: 80vh;
  overflow-y: auto;
  background-color: transparent;
}

.message {
  margin-bottom: 18px;
  display: flex;
  align-items: flex-start;
  max-width: 90%;
}

.message.assistant {
  flex-direction: row;
}

.message.user {
  flex-direction: row-reverse;
  align-self: flex-end;
  margin-left: auto;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  overflow: hidden;
  margin: 0 8px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  border: none;
}

.assistant .avatar {
  background-color: #fff;
  color: #8e7cc3;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.user .avatar {
  background-color: #8e7cc3;
  color: white;
  box-shadow: 0 1px 3px rgba(142, 124, 195, 0.3);
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 5px;
  font-size: 15px;
  line-height: 1.5;
  position: relative;
  max-width: 100%;
}

.assistant .message-bubble {
  background-color: #fff;
  color: #333;
  border: 1px solid #e8e8e8;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.user .message-bubble {
  background-color: #d8cff5;
  color: #333;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 选项按钮 */
.options-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
}

.option-btn {
  padding: 10px 14px;
  background-color: white;
  border: 1px solid #e8e3f5;
  border-radius: 18px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #8e7cc3;
}

.option-btn:hover {
  background-color: #f9f8ff;
}

.option-btn.selected {
  background-color: #8e7cc3;
  color: white;
  border-color: #8e7cc3;
}

.option-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

/* 输入区域 */
.input-container {
  position: fixed;
  bottom: 5px;
  left: 0;
  right: 0;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 12px 14px;
  display: flex;
  align-items: center;
  z-index: 5;
  border-top: 1px solid #e8e8e8;
}

.text-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e8e8e8;
  border-radius: 20px;
  font-size: 15px;
  outline: none;
  transition: border-color 0.2s;
  background-color: #f5f5f5;
}

.text-input:focus {
  border-color: #8e7cc3;
  background-color: #fff;
}

.send-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #8e7cc3;
  color: white;
  border: none;
  margin-left: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.send-btn:disabled {
  background-color: #d0d0d0;
  cursor: not-allowed;
}

.send-btn:not(:disabled):hover {
  background-color: #7c6ab0;
}

/* 底部标签栏 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 70px;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  border-top: 1px solid #e8e8e8;
  z-index: 10;
  padding: 0 10px;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  color: #8e8e93;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 8px;
  margin: 5px;
}

.tab-item.active {
  color: #8e7cc3;
  background-color: rgba(142, 124, 195, 0.08);
}

.tab-icon {
  font-size: 20px;
  margin-bottom: 4px;
  transition: all 0.2s ease;
}

.tab-item.active .tab-icon {
  transform: translateY(-2px);
}

/* 输入指示器 */
.typing-indicator {
  display: flex;
  padding: 10px 14px;
}

.typing-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #b8a9d9;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(1) {
  animation-delay: 0s;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.3s ease forwards;
}

@keyframes typing {
  0% {
    opacity: 0.3;
    transform: scale(0.9);
  }
  50% {
    opacity: 1;
    transform: scale(1.1);
  }
  100% {
    opacity: 0.3;
    transform: scale(0.9);
  }
}

/* 装饰元素 */
.decoration {
  position: absolute;
  z-index: 0;
  opacity: 0.05;
}

.leaf-1 {
  top: 10%;
  left: 5%;
  transform: rotate(45deg);
  font-size: 60px;
  color: #8e7cc3;
}

.leaf-2 {
  bottom: 25%;
  right: 5%;
  transform: rotate(-20deg);
  font-size: 50px;
  color: #8e7cc3;
}
</style>
